package com.flute.icrawler.app.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.cyberneko.html.parsers.DOMParser;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class StaticParserDocment extends AbstractParserDocment {

	public StaticParserDocment(String strUrl, String charset,
			InputStream sourceInputStream) {
		super(strUrl, charset, sourceInputStream);
	}

	public StaticParserDocment(String strUrl, String charset, byte[] content) {
		super(strUrl, charset, content);
	}

	@Override
	protected Document getDocument() throws ParserException {
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new InputStreamReader(
					sourceInputStream, charset));

			DOMParser parser = new DOMParser();

			parser.setFeature("http://xml.org/sax/features/namespaces", false);
			parser.setProperty(
					"http://cyberneko.org/html/properties/names/elems", "upper");
			parser.setProperty(
					"http://cyberneko.org/html/properties/names/attrs", "lower");

			parser.parse(new InputSource(reader));
			return parser.getDocument();

		} catch (UnsupportedEncodingException e) {

			throw new ParserException("unsupported encoding(" + getCharset()
					+ "):" + e.getMessage());
		} catch (SAXException e) {

			throw new ParserException("parser html error-SAXException:"
					+ e.getMessage());
		} catch (IOException e) {

			throw new ParserException("read html source error:"
					+ e.getMessage());
		} finally {
			try {
				reader.close();
				sourceInputStream.close();
			} catch (IOException e) {
			}
		}
	}

}
